<template>
  <div class="mb-5">
    <div class="flex items-center mb-3">
      <img src="./assets/grid.png" alt="Grid" class="w-6 h-6 mr-2" />
      <h3 class="text-lg font-medium">Grid</h3>
      <div class="ml-10">
        <ToggleGroup v-model="activeTab" :options="tabOptions" />
      </div>
    </div>
    <div class="grid grid-cols-5 gap-3">
      <!-- 电网消耗折线图 -->
      <div class="grid-line-chart col-span-3 chart-box">
        <h4 class="text-base font-medium text-gray-800">Net Grid Consumption</h4>
        <div class="text-3xl font-bold mt-2 mb-4 text-gray-900">
          {{ totalPower }}
        </div>
        <div class="text-sm text-gray-500 mb-4">Home Power (kWh)</div>
        <div ref="lineChartRef" class="chart-container" style="height: 260px"></div>
      </div>

      <!-- 电网交互饼图 -->
      <div class="grid-pie-chart col-span-2 chart-box">
        <h4 class="text-base font-medium text-gray-800">
          {{ activeTab === "export" ? "Export to Grid" : "Import from Grid" }}
        </h4>
        <div class="mt-6">
          <div ref="pieChartRef" class="chart-container" style="height: 280px">
            <div ref="pieContainer" class="w-full h-full"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, nextTick, markRaw } from "vue";
import { getMockData, calculateTotals, calculatePieData } from "./mock";
import * as echarts from "echarts/core";
import { TitleComponent, TooltipComponent, LegendComponent } from "echarts/components";
import { LineChart, PieChart, BarChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";
import ToggleGroup from "@/components/ToggleGroup/index.vue";

// 组件props
interface Props {
  timeScope?: "day" | "week" | "month" | "year";
  dataType?: "data" | "analysis";
  processedData?: any;
  energyTotals?: any;
  isLoading?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  timeScope: "day",
  dataType: "data",
  isLoading: false
});

// 注册 ECharts 组件
echarts.use([TitleComponent, TooltipComponent, LegendComponent, LineChart, PieChart, BarChart, CanvasRenderer]);

const activeTab = ref("export");

const tabOptions = [
  { label: "Export to Grid", value: "export" },
  { label: "Import from Grid", value: "import" }
];

// 图表ref
const lineChartRef = ref<HTMLElement | null>(null);
const pieChartRef = ref<HTMLElement | null>(null);
const pieContainer = ref<HTMLElement | null>(null);

// ECharts实例
let lineChart: echarts.ECharts | null = null;
let pieChart: echarts.ECharts | null = null;

// 计算属性 - 获取当前数据
const currentData = computed(() => {
  return getMockData(props.timeScope, props.dataType, activeTab.value as "export" | "import");
});

// 计算属性 - 汇总数据
const summaryData = computed(() => {
  return calculateTotals(currentData.value.energyData, activeTab.value as "export" | "import");
});

// 计算属性 - 饼状图数据
const pieData = computed(() => {
  return calculatePieData(currentData.value.energyData, activeTab.value as "export" | "import");
});

// 计算属性 - 图表类型
const chartType = computed(() => {
  return props.timeScope === "day" ? "line" : "bar";
});

// 计算属性 - 总功率显示
const totalPower = computed(() => {
  if (props.energyTotals) {
    const total = activeTab.value === "export" ? props.energyTotals.gridToGrid : props.energyTotals.gridFromGrid;
    return (total / 1000).toFixed(2) + " kWh";
  }
  return "0.00 kWh";
});

// 创建主图表配置
const createMainChartOption = () => {
  const isLine = chartType.value === "line";
  const isAnalysis = props.dataType === "analysis";
  const mode = activeTab.value;

  let chartData: number[] = [];
  let timePoints: string[] = [];

  if (props.dataType === "data" && props.processedData) {
    // 使用真实数据
    chartData = mode === "export" ? props.processedData.grid1Output : props.processedData.grid1Input;
    timePoints = props.processedData.timePoints;
    console.log("GridCard 使用真实数据:", {
      mode,
      chartData: chartData?.slice(0, 5),
      timePoints: timePoints?.slice(0, 5),
      dataLength: chartData?.length
    });
  } else {
    // 使用mock数据
    const mockData = getMockData(props.timeScope, props.dataType);
    chartData = mockData.energyData;
    timePoints = mockData.timePoints;
    console.log("GridCard 使用mock数据:", {
      mode,
      chartData: chartData?.slice(0, 5),
      timePoints: timePoints?.slice(0, 5)
    });
  }

  // 颜色配置 - 根据模式设置不同颜色
  const colors =
    mode === "export"
      ? {
          solar: "#fcc419", // 黄色 - 太阳能
          battery: "#3498db", // 蓝色 - 电池
          home: "#10b981" // 绿色 - 家庭 (未使用在export模式)
        }
      : {
          solar: "#fcc419", // 黄色 - 太阳能 (未使用在import模式)
          battery: "#3498db", // 蓝色 - 电池
          home: "#10b981" // 绿色 - 家庭
        };

  return {
    grid: {
      left: "3%",
      right: "4%",
      bottom: isAnalysis ? "15%" : "10%", // Analysis模式下为legend留出更多空间
      top: "5%",
      containLabel: true
    },
    tooltip: {
      trigger: "axis",
      formatter: (params: any) => {
        if (isAnalysis) {
          // Analysis模式下的详细提示
          const point = params[0];
          // const energyPoint = data.energyData[point.dataIndex];
          if (mode === "export") {
            return `
              <div><strong>${point.name}</strong></div>
              <div style="color: ${colors.solar}">● Solar: ${energyPoint.solar} kWh</div>
              <div style="color: ${colors.battery}">● Battery: ${energyPoint.battery} kWh</div>
            `;
          } else {
            return `
              <div><strong>${point.name}</strong></div>
              <div style="color: ${colors.battery}">● To Battery: ${energyPoint.battery} kWh</div>
              <div style="color: ${colors.home}">● To Home: ${energyPoint.home} kWh</div>
            `;
          }
        } else {
          // Data模式下的简单提示
          const point = params[0];
          const energyPoint = chartData[point.dataIndex];
          // console.log("point====>", point, energyPoint);
          return `<div><strong>${point.name}</strong></div>
            <div>Total: ${point.value} kWh</div>`;
          return `
            <div><strong>${point.name}</strong></div>
            <div>Total: ${point.value} kWh</div>
            ${
              mode === "export"
                ? `
              <div>Solar: ${energyPoint.solar} kWh</div>
              <div>Battery: ${energyPoint.battery} kWh</div>
            `
                : `
              <div>To Battery: ${energyPoint.battery} kWh</div>
              <div>To Home: ${energyPoint.home} kWh</div>
            `
            }
          `;
        }
      }
    },
    legend: isAnalysis
      ? {
          data:
            mode === "export"
              ? [
                  {
                    name: "Solar",
                    icon: "circle",
                    textStyle: { color: colors.solar }
                  },
                  {
                    name: "Battery",
                    icon: "circle",
                    textStyle: { color: colors.battery }
                  }
                ]
              : [
                  {
                    name: "Battery",
                    icon: "circle",
                    textStyle: { color: colors.battery }
                  },
                  {
                    name: "Home",
                    icon: "circle",
                    textStyle: { color: colors.home }
                  }
                ],
          bottom: 5,
          left: "center",
          itemGap: 20,
          textStyle: {
            color: "#666",
            fontSize: 12
          }
        }
      : undefined,
    xAxis: {
      type: "category",
      data: timePoints,
      axisLabel: {
        color: "#333"
      },
      axisLine: {
        lineStyle: {
          color: "#E0E0E0"
        }
      }
    },
    yAxis: {
      type: "value",
      axisLine: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: "#F5F5F5"
        }
      }
    },
    series: isAnalysis
      ? (() => {
          if (mode === "export") {
            return [
              // Export模式：显示Solar和Battery
              {
                name: "Solar",
                data: chartData, // 在analysis模式下需要进一步处理
                type: isLine ? "line" : "bar",
                smooth: isLine,
                stack: isLine ? undefined : "total",
                lineStyle: isLine ? { color: colors.solar, width: 3 } : undefined,
                itemStyle: { color: colors.solar },
                symbol: isLine ? "circle" : undefined,
                symbolSize: isLine ? 6 : undefined,
                areaStyle: isLine
                  ? {
                      color: {
                        type: "linear",
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                          { offset: 0, color: colors.solar + "40" },
                          { offset: 1, color: colors.solar + "05" }
                        ]
                      }
                    }
                  : undefined
              },
              {
                name: "Battery",
                data: chartData, // 在analysis模式下需要进一步处理
                type: isLine ? "line" : "bar",
                smooth: isLine,
                stack: isLine ? undefined : "total",
                lineStyle: isLine ? { color: colors.battery, width: 3 } : undefined,
                itemStyle: { color: colors.battery },
                symbol: isLine ? "circle" : undefined,
                symbolSize: isLine ? 6 : undefined,
                areaStyle: isLine
                  ? {
                      color: {
                        type: "linear",
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                          { offset: 0, color: colors.battery + "40" },
                          { offset: 1, color: colors.battery + "05" }
                        ]
                      }
                    }
                  : undefined
              }
            ];
          } else {
            return [
              // Import模式：显示Battery和Home
              {
                name: "Battery",
                data: chartData, // 在analysis模式下需要进一步处理
                type: isLine ? "line" : "bar",
                smooth: isLine,
                stack: isLine ? undefined : "total",
                lineStyle: isLine ? { color: colors.battery, width: 3 } : undefined,
                itemStyle: { color: colors.battery },
                symbol: isLine ? "circle" : undefined,
                symbolSize: isLine ? 6 : undefined,
                areaStyle: isLine
                  ? {
                      color: {
                        type: "linear",
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                          { offset: 0, color: colors.battery + "40" },
                          { offset: 1, color: colors.battery + "05" }
                        ]
                      }
                    }
                  : undefined
              },
              {
                name: "Home",
                data: chartData, // 在analysis模式下需要进一步处理
                type: isLine ? "line" : "bar",
                smooth: isLine,
                stack: isLine ? undefined : "total",
                lineStyle: isLine ? { color: colors.home, width: 3 } : undefined,
                itemStyle: { color: colors.home },
                symbol: isLine ? "circle" : undefined,
                symbolSize: isLine ? 6 : undefined,
                areaStyle: isLine
                  ? {
                      color: {
                        type: "linear",
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                          { offset: 0, color: colors.home + "40" },
                          { offset: 1, color: colors.home + "05" }
                        ]
                      }
                    }
                  : undefined
              }
            ];
          }
        })()
      : [
          // Data模式：显示总计
          {
            name: "Total Energy",
            data: chartData,
            type: isLine ? "line" : "bar",
            smooth: isLine,
            lineStyle: isLine ? { color: "#ffbb33", width: 3 } : undefined,
            itemStyle: { color: "#ffbb33" },
            symbol: isLine ? "none" : undefined,
            areaStyle: isLine
              ? {
                  color: {
                    type: "linear",
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                      { offset: 0, color: "rgba(255, 187, 51, 0.3)" },
                      { offset: 1, color: "rgba(255, 187, 51, 0.02)" }
                    ]
                  }
                }
              : undefined
          }
        ]
  };
};

// 创建饼图配置
const createPieChartOption = () => {
  return {
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} kWh ({d}%)"
    },
    series: [
      {
        name: activeTab.value === "export" ? "Export to Grid" : "Import from Grid",
        type: "pie",
        radius: ["40%", "70%"],
        center: ["50%", "50%"],
        avoidLabelOverlap: false,
        padAngle: 8,
        itemStyle: {
          borderColor: "#fff",
          borderWidth: 3,
          borderRadius: 8
        },
        label: {
          show: true,
          position: "outside",
          formatter: function (params: any) {
            return `{name|${params.name}}\n{value|${params.value} kWh}\n{percent|${params.percent}%}`;
          },
          rich: {
            name: {
              fontSize: 12,
              color: "#333",
              fontWeight: "bold"
            },
            value: {
              fontSize: 11,
              color: "#666",
              lineHeight: 16
            },
            percent: {
              fontSize: 11,
              color: "#999",
              lineHeight: 16
            }
          }
        },
        labelLine: {
          show: true,
          length: 10,
          length2: 20,
          lineStyle: {
            color: "#999"
          }
        },
        emphasis: {
          scale: true,
          scaleSize: 5,
          itemStyle: {
            borderColor: "#fff",
            borderWidth: 3,
            borderRadius: 8,
            shadowBlur: 15,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.3)"
          }
        },
        data: pieData.value.map((item) => ({
          value: item.value,
          name: item.name,
          itemStyle: {
            color: item.color,
            borderColor: "#fff",
            borderWidth: 3,
            borderRadius: 8
          }
        }))
      }
    ]
  };
};

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    // 初始化主图表
    if (lineChartRef.value) {
      lineChart = markRaw(echarts.init(lineChartRef.value));
      lineChart.setOption(createMainChartOption());

      window.addEventListener("resize", () => {
        lineChart?.resize();
      });
    }

    // 初始化饼图
    if (pieContainer.value) {
      pieChart = markRaw(echarts.init(pieContainer.value));
      pieChart.setOption(createPieChartOption());

      window.addEventListener("resize", () => {
        pieChart?.resize();
      });
    }
  });
};

// 更新图表
const updateCharts = () => {
  if (lineChart) {
    lineChart.setOption(createMainChartOption(), true);
  }
  if (pieChart) {
    pieChart.setOption(createPieChartOption(), true);
  }
};

// 监听props变化，更新图表
watch(
  [() => props.processedData, () => props.energyTotals, () => props.dataType, () => activeTab.value],
  () => {
    console.log("GridCard 监听到props变化:", {
      hasProcessedData: !!props.processedData,
      grid1InputLength: props.processedData?.grid1Input?.length,
      grid1OutputLength: props.processedData?.grid1Output?.length,
      dataType: props.dataType,
      activeTab: activeTab.value,
      hasEnergyTotals: !!props.energyTotals
    });

    if (props.processedData && (props.processedData.grid1Input || props.processedData.grid1Output)) {
      nextTick(() => {
        console.log("GridCard 开始更新图表");
        updateCharts();
      });
    }
  },
  { deep: true, immediate: true }
);

// 图表自适应
const resizeCharts = () => {
  if (lineChart) {
    lineChart.resize();
  }
  if (pieChart) {
    pieChart.resize();
  }
};

onMounted(() => {
  initCharts();
  window.addEventListener("resize", resizeCharts);
});

onUnmounted(() => {
  window.removeEventListener("resize", resizeCharts);
  if (lineChart) {
    lineChart.dispose();
    lineChart = null;
  }
  if (pieChart) {
    pieChart.dispose();
    pieChart = null;
  }
});
</script>

<style scoped>
.chart-box {
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.chart-container {
  background: transparent;
  border-radius: 8px;
  padding: 0;
}
</style>
